﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell;
using System.ComponentModel.Design;
using EnvDTE;

namespace ScaffoldIt.Commands
{
    class ScaffoldItFromCodeCommand : OleMenuCommand
    {
        EnvDTE80.DTE2 _dte;

        private ProjectItem _currentItem;
        private CodeClass _class;
        
        public ScaffoldItFromCodeCommand()
            : base(Callback, new CommandID(GuidList.guidScaffoldItCmdSet, (int)PkgCmdIDList.cmdScaffoldItFromCode))
        {
            this.BeforeQueryStatus += new EventHandler(CmdBeforeQueryStatus);
        }

        void CmdBeforeQueryStatus(object sender, EventArgs e)
        {
            if (ConfigHelpers.HasConfig())
            {
                _dte = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));
                var currentFile = _dte.CurrentFile();
                if (currentFile != null)
                {
                    _currentItem = _dte.Solution.FindProjectItem(currentFile);
                    if (_currentItem != null)
                    {
                        _class = _dte.CurrentCodeClass(currentFile, _currentItem);
                        if (_class != null)
                        {
                            Visible = true;
                            return;
                        }
                    }
                }
            }
            
            Visible = false;
        }

        static void Callback(object sender, EventArgs e)
        {
            ScaffoldItFromCodeCommand cmd = sender as ScaffoldItFromCodeCommand;

            ScaffoldingContext ctx = new ScaffoldingContext();
            try
            {
                cmd.Send(ctx);
            }
            catch (Exception ex)
            {
                ctx.Output.WriteLine(ex.ToString());
            }
        }

        private void Send(ScaffoldingContext ctx)
        {
            if (ctx.Init())
            {
                var models = ctx.GetModelFor(_currentItem, _class);
                if (models == null) return;

                ctx.Scaffold(new[] { models });
            }
        }
    }
}
